#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: redis_clients.py
@contact: zwb15083976291@163.com
@time: 2021/11/14
"""
import traceback

from django_redis import get_redis_connection
from redis import RedisError


class RedisClient(object):

    def __init__(self, alias='default'):
        self.redis_client = get_redis_connection(alias)

    def __getattr__(self, item):
        if hasattr(self.redis_client, item):
            return getattr(self.redis_client, item)
        raise RedisError('redis client has not attribute :{}'.format(item))

    def get_decode_response_or_not(self, key, decode_response=True, encoding='utf-8'):
        """返回解码或者不解码的结果"""
        try:
            value = self.redis_client.get(key)
        except Exception:
            raise RedisError(traceback.format_exc())
        if decode_response:
            return value.decode(encoding=encoding) if value else ''
        return value

    def delete(self, *names):
        try:
            return self.redis_client.delete(*names)
        except Exception:
            raise RedisError(traceback.format_exc())

    def set(self, key, value, ex=None):
        try:
            return self.redis_client.set(key, value, ex)
        except Exception:
            raise RedisError(traceback.format_exc())

    def hset(self, name, key=None, value=None, mapping=None):
        try:
            return getattr(self.redis_client, 'hset')(name, key, value, mapping)
        except Exception:
            raise RedisError(traceback.format_exc())

    def hget__decode_response_or_not(self, name, key, decode_response=True, encoding="utf-8"):
        value = getattr(self.redis_client, 'hget')(name, key)
        if decode_response:
            return value.decode(encoding=encoding) if value else ''
        return value
